package com.cai.server;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * UDP服务
 */
@Component
public class WebServer {
    @Autowired
    private RedisTemplate<String,Integer> redisTemplate;
    private static final DatagramSocket socket;

    static {
        try {
            socket = new DatagramSocket(9999);
        } catch (SocketException e) {
            throw new RuntimeException(e);
        }
    }
    private static final byte[] receiveData = new byte[1024];

    private void createServer(){
        try {
            // 创建数据包对象来接收客户端发送的数据
            DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
            // 接收数据包
            socket.receive(receivePacket);
            // 从数据包中提取客户端发送的数据和信息
            String clientData = new String(receivePacket.getData(), 0, receivePacket.getLength());
            InetAddress clientAddress = receivePacket.getAddress();
            int clientPort = receivePacket.getPort();
            //存储客户端地址和端口
            System.out.println("Received from client at " + clientAddress + ":" + clientPort + ": " + clientData);
            // 构造回应数据
            String responseData = "来自" + clientAddress + "的消息：" + clientData;
            byte[] sendData = responseData.getBytes();
            Map<Object, Object> port = redisTemplate.opsForHash().entries("port");
            for (Map.Entry<Object, Object> entry : port.entrySet()) {
                if (!entry.getValue().equals(clientPort)) {
                    // 创建数据包用于发送回应
                    DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, clientAddress, clientPort);
                    // 发送回应数据包
                    socket.send(sendPacket);
                }
            }
            createServer();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public void task(){
        ExecutorService executor= Executors.newFixedThreadPool(3);
        executor.submit(this::createServer);
    }
}
